using AdmissionQA.Application.Dtos.QAHistory;
using AdmissionQA.Application.ServiceInterfaces;
using Microsoft.AspNetCore.Mvc;

namespace AdmissionQA.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
public class SmartQAController(
    IServiceProvider serviceProvider,
    IQAHistoryServices qaHistoryServices) : ControllerBase
{
    private readonly IServiceProvider _serviceProvider = serviceProvider;
    private readonly IQAHistoryServices _qaHistoryServices = qaHistoryServices;

    /// <summary>
    /// 统一智能问答接口 - 根据查询内容自动选择最相关的模块进行回答
    /// </summary>
    /// <param name="query">用户问题</param>
    /// <param name="topK">每个模块返回的结果数量，默认3个</param>
    /// <returns>综合的智能问答结果</returns>
    [HttpGet("unified-qa")]
    public async Task<IActionResult> UnifiedQA([FromQuery] string query, [FromQuery] int topK = 3)
    {
        if (string.IsNullOrWhiteSpace(query))
        {
            return BadRequest("问题不能为空");
        }

        var results = new List<object>();
        var moduleResults = new Dictionary<string, object>();

        try
        {
            // 顺序查询各个模块，避免DbContext并发问题
            var issueResult = await QueryIssues(query, topK);
            if (issueResult != null) moduleResults["问答库"] = issueResult;

            var policyResult = await QueryAdmissionPolicies(query, topK);
            if (policyResult != null) moduleResults["招生政策"] = policyResult;

            var majorResult = await QueryMajorInfos(query, topK);
            if (majorResult != null) moduleResults["专业信息"] = majorResult;

            var scholarshipResult = await QueryScholarshipInfos(query, topK);
            if (scholarshipResult != null) moduleResults["奖学金信息"] = scholarshipResult;

            var campusResult = await QueryCampusLifes(query, topK);
            if (campusResult != null) moduleResults["校园生活"] = campusResult;

            var tuitionResult = await QueryTuitionFees(query, topK);
            if (tuitionResult != null) moduleResults["学费信息"] = tuitionResult;

            // 记录问答历史
            var qaHistory = new QAHistoryDto
            {
                Query = query,
                Answer = $"查询了{moduleResults.Count}个模块，找到相关结果",
                QueryType = "统一智能问答",
                Confidence = moduleResults.Count > 0 ? "高" : "低",
                UserIP = HttpContext.Connection.RemoteIpAddress?.ToString(),
                UserAgent = HttpContext.Request.Headers["User-Agent"].ToString()
            };

            await _qaHistoryServices.CreateQAHistoryAsync(qaHistory);

            return Ok(new
            {
                Query = query,
                TotalModules = moduleResults.Count,
                Results = moduleResults,
                Timestamp = DateTime.Now,
                Source = "统一智能问答系统"
            });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new
            {
                Query = query,
                Error = "智能问答服务暂时不可用，请稍后重试",
                Details = ex.Message,
                Source = "统一智能问答系统"
            });
        }
    }

    /// <summary>
    /// 智能推荐 - 根据用户问题推荐最相关的信息
    /// </summary>
    /// <param name="query">用户问题</param>
    /// <returns>最相关的推荐结果</returns>
    [HttpGet("smart-recommend")]
    public async Task<IActionResult> SmartRecommend([FromQuery] string query)
    {
        if (string.IsNullOrWhiteSpace(query))
        {
            return BadRequest("问题不能为空");
        }

        try
        {
            // 获取所有模块的最佳匹配
            var bestMatches = new List<object>();

            using (var scope1 = _serviceProvider.CreateScope())
            {
                var issueServices = scope1.ServiceProvider.GetRequiredService<IIssueServices>();
                var issueResult = await issueServices.SearchIssuesByEmbeddingAsync(query, 1);
                if (issueResult.Data?.Any() == true)
                {
                    var best = issueResult.Data.First();
                    bestMatches.Add(new
                    {
                        Module = "智能问答",
                        Question = best.Question,
                        Answer = best.Answer,
                        Confidence = "高"
                    });
                }
            }

            using (var scope2 = _serviceProvider.CreateScope())
            {
                var admissionPolicyServices = scope2.ServiceProvider.GetRequiredService<IAdmissionPolicyServices>();
                var policyResult = await admissionPolicyServices.SearchAdmissionPoliciesByEmbeddingAsync(query, 1);
                if (policyResult.Data?.Any() == true)
                {
                    var best = policyResult.Data.First();
                    bestMatches.Add(new
                    {
                        Module = "招生政策",
                        PolicyName = best.AdmissionPolicyName,
                        Content = best.AdmissionPolicyContent,
                        Confidence = "高"
                    });
                }
            }

            using (var scope3 = _serviceProvider.CreateScope())
            {
                var majorInfoServices = scope3.ServiceProvider.GetRequiredService<IMajorInfoServices>();
                var majorResult = await majorInfoServices.SearchMajorInfosByEmbeddingAsync(query, 1);
                if (majorResult.Data?.Any() == true)
                {
                    var best = majorResult.Data.First();
                    bestMatches.Add(new
                    {
                        Module = "专业信息",
                        MajorName = best.MajorName,
                        Description = best.Description,
                        Confidence = "高"
                    });
                }
            }

            // 记录推荐历史
            var qaHistory = new QAHistoryDto
            {
                Query = query,
                Answer = $"为您推荐了{bestMatches.Count}个相关结果",
                QueryType = "智能推荐",
                Confidence = bestMatches.Count > 0 ? "高" : "低",
                UserIP = HttpContext.Connection.RemoteIpAddress?.ToString(),
                UserAgent = HttpContext.Request.Headers["User-Agent"].ToString()
            };

            await _qaHistoryServices.CreateQAHistoryAsync(qaHistory);

            return Ok(new
            {
                Query = query,
                Recommendations = bestMatches,
                TotalRecommendations = bestMatches.Count,
                Timestamp = DateTime.Now,
                Source = "智能推荐系统"
            });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new
            {
                Query = query,
                Error = "智能推荐服务暂时不可用，请稍后重试",
                Details = ex.Message,
                Source = "智能推荐系统"
            });
        }
    }

    /// <summary>
    /// 获取热门问题统计
    /// </summary>
    /// <returns>热门问题统计信息</returns>
    [HttpGet("popular-questions")]
    public async Task<IActionResult> GetPopularQuestions()
    {
        try
        {
            var popularQueries = await _qaHistoryServices.GetPopularQueriesAsync(10);
            var statistics = await _qaHistoryServices.GetQueryStatisticsAsync();

            return Ok(new
            {
                PopularQueries = popularQueries,
                Statistics = statistics,
                Timestamp = DateTime.Now,
                Source = "智能问答统计系统"
            });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new
            {
                Error = "获取统计信息失败",
                Details = ex.Message,
                Source = "智能问答统计系统"
            });
        }
    }

    private async Task<object?> QueryIssues(string query, int topK)
    {
        using var scope = _serviceProvider.CreateScope();
        var issueServices = scope.ServiceProvider.GetRequiredService<IIssueServices>();
        var result = await issueServices.SearchIssuesByEmbeddingAsync(query, topK);
        return result.Data?.Any() == true ? result.Data : null;
    }

    private async Task<object?> QueryAdmissionPolicies(string query, int topK)
    {
        using var scope = _serviceProvider.CreateScope();
        var admissionPolicyServices = scope.ServiceProvider.GetRequiredService<IAdmissionPolicyServices>();
        var result = await admissionPolicyServices.SearchAdmissionPoliciesByEmbeddingAsync(query, topK);
        return result.Data?.Any() == true ? result.Data : null;
    }

    private async Task<object?> QueryMajorInfos(string query, int topK)
    {
        using var scope = _serviceProvider.CreateScope();
        var majorInfoServices = scope.ServiceProvider.GetRequiredService<IMajorInfoServices>();
        var result = await majorInfoServices.SearchMajorInfosByEmbeddingAsync(query, topK);
        return result.Data?.Any() == true ? result.Data : null;
    }

    private async Task<object?> QueryScholarshipInfos(string query, int topK)
    {
        using var scope = _serviceProvider.CreateScope();
        var scholarshipInfoServices = scope.ServiceProvider.GetRequiredService<IScholarshipInfoServices>();
        var result = await scholarshipInfoServices.SearchScholarshipInfosByEmbeddingAsync(query, topK);
        return result.Data?.Any() == true ? result.Data : null;
    }

    private async Task<object?> QueryCampusLifes(string query, int topK)
    {
        using var scope = _serviceProvider.CreateScope();
        var campusLifeServices = scope.ServiceProvider.GetRequiredService<ICampusLifeServices>();
        var result = await campusLifeServices.SearchCampusLifesByEmbeddingAsync(query, topK);
        return result.Data?.Any() == true ? result.Data : null;
    }

    private async Task<object?> QueryTuitionFees(string query, int topK)
    {
        using var scope = _serviceProvider.CreateScope();
        var tuitionFeeServices = scope.ServiceProvider.GetRequiredService<ITuitionFeeServices>();
        var result = await tuitionFeeServices.SearchTuitionFeesByEmbeddingAsync(query, topK);
        return result.Data?.Any() == true ? result.Data : null;
    }
} 